package com.hot100.mid;

/**
 * @author zhengTao
 * @version 1.0
 * @description: 在排序数组中查找元素的第一个和最后一个位置  ,同Demo11也是二分查找
 * @date 2022/8/6 16:55
 */
public class Demo12 {

    public int[] searchRange(int[] nums, int target) {
          int[] res={-1,-1};
          if(nums.length==1&&nums[0]==target){
              return new int[]{0,0};
          }
          res[0]=binarySearch(nums,target,true);
          res[1]=binarySearch(nums,target,false);

          return res;
    }
    //二分查找寻找左右边界，true寻找左边界，false寻找又边界
    private int binarySearch(int[] nums, int target, boolean b) {
        int left=0,right=nums.length-1,res=-1;
        while (left<=right){
            int mid=left+(right-left)/2;
            if(nums[mid]<target){
                left=mid+1;
            }else if(nums[mid]>target){
                right=mid-1;
            }else {
                //正好等于mid
                res=mid;
                if(b){
                    right=mid-1;
                }else {
                    left=mid+1;
                }
            }
        }
        return res;
    }
}
